﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Able.Api.Tests
{
    public class ApiHelper
    {
        //public const string Url = "https://api.easesales.com/easesales/api/";
        public const string Url = "http://localhost:1111/api/";

        public static string SendGet(string url, Dictionary<string, object> parameters = null, List<string> list = null)
        {
            string data = string.Empty;
            if (list != null)
            {
                foreach (var item in parameters)
                {
                    list.Add(item.Key + "_" + item.Value);
                }
                data = ApiHelper.BuildQuery(list, "utf-8");
            }
            else
            {
                data = ApiHelper.BuildQuery(parameters, "utf-8");
            }
            if (!string.IsNullOrEmpty(data))
            {
                url = url + "?" + data;
            }
            //创建请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            //GET请求
            request.Method = "GET";
            request.ReadWriteTimeout = 5000000;
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));

            //返回内容
            string retString = myStreamReader.ReadToEnd();
            return retString;
        }
        /// <summary>
        /// Http (GET/POST)
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="method">请求方法</param>
        /// <returns>响应内容</returns>
        /// <returns>响应内容</returns>
        public static string SendPost(string url, Dictionary<string, object> parameters, List<string> list = null)
        {
            var client = new WebClient();
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            client.Encoding = Encoding.UTF8;
            string data = string.Empty;

            if (list != null)
            {
                if (parameters != null)
                {
                    foreach (var item in parameters)
                    {
                        list.Add(item.Key + "_" + item.Value);
                    }
                }
                data = ApiHelper.BuildQuery(list, "utf-8");
            }
            else
            {
                if (parameters != null)
                {
                    data = ApiHelper.BuildQuery(parameters, "utf-8");
                }
            }
            var str = client.UploadString(url, "POST", data);
            return str;
        }

        public static string SendPost(string url, string data)
        {
            var client = new WebClient();
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            client.Encoding = Encoding.UTF8;

            //if (!data.StartsWith("?"))
            //{
            //    data = "?" + data;
            //}
            var str = client.UploadString(url, "POST", data);
            return str;
        }
        public static string SendPost(string url, List<string> list = null)
        {
            return SendPost(url, null, list);
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery(IDictionary<string, object> parameters, string encode = "utf-8")
        {
            if (parameters == null) return string.Empty;
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            IEnumerator<KeyValuePair<string, object>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value.ToString();
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    if (encode == "gb2312")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                    }
                    else if (encode == "utf8")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                    hasParam = true;
                }
            }
            return postData.ToString();
        }
        public static string BuildQuery(List<string> list, string encode = "utf-8")
        {
            if (list == null) return string.Empty;
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            foreach (var item in list)
            {
                var arr = item.Split('_');
                if (arr.Length == 2)
                {
                    string name = arr[0];
                    string value = arr[1];

                    // 忽略参数名或参数值为空的参数
                    if (!string.IsNullOrEmpty(name)) //&& !string.IsNullOrEmpty(value)
                    {
                        if (hasParam)
                        {
                            postData.Append("&");
                        }
                        postData.Append(name);
                        postData.Append("=");
                        if (encode == "gb2312")
                        {
                            postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                        }
                        else if (encode == "utf8")
                        {
                            postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                        }
                        else
                        {
                            postData.Append(value);
                        }
                        hasParam = true;
                    }
                }
            }
            return postData.ToString();
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }


        #region 6.0 上传多个文件和参数
        /// <summary>
        /// HttpUploadFile
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paths"></param>
        /// <param name="names">文件在服務接收時的名字</param>
        /// <param name="data"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string UploadFiles(string url, string[] paths, string[] names, Dictionary<string, string> data, Encoding encoding)
        {
            //必须
            string boundary = DateTime.Now.Ticks.ToString("X");
            //必须的

            //form 开始标志
            byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            //form 结尾标志
            byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

            //1.HttpWebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            request.Credentials = CredentialCache.DefaultCredentials;

            using (Stream stream = request.GetRequestStream())
            {
                //传递参数模板 Content-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}
                //1.1 key/value
                string formdataTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}";
                //传递参数
                if (data != null)
                {
                    foreach (string key in data.Keys)
                    {
                        //传递参数开始标识
                        stream.Write(boundarybytes, 0, boundarybytes.Length);

                        string formitem = string.Format(formdataTemplate, key, data[key]);

                        byte[] formitembytes = encoding.GetBytes(formitem);

                        stream.Write(formitembytes, 0, formitembytes.Length);
                    }
                }

                //上传文件模板
                //1.2 file
                string headerTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";

                byte[] buffer = new byte[6 * 1024 * 1024];

                for (int i = 0; i < paths.Length; i++)
                {
                    //上传文件标识
                    stream.Write(boundarybytes, 0, boundarybytes.Length);

                    string header = string.Format(headerTemplate, names[i], Path.GetFileName(paths[i]));

                    byte[] headerbytes = encoding.GetBytes(header);

                    stream.Write(headerbytes, 0, headerbytes.Length);

                    //将文件流读入到请求流中
                    using (FileStream fileStream = new FileStream(paths[i], FileMode.Open, FileAccess.Read))
                    {
                        int r = fileStream.Read(buffer, 0, buffer.Length);
                        stream.Write(buffer, 0, r);
                    }
                }

                //form 结束标志
                //1.3 form end
                stream.Write(endbytes, 0, endbytes.Length);
            }
            //2.WebResponse
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {

                string result = stream.ReadToEnd();
                return result;
            }
        }

        #endregion
    }

    public class Result
    {
        public int status { get; set; }
        public string msg { get; set; }
        public object data { get; set; }
    }

}
